package com.qianxx.base;

import android.content.Context;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.qianxx.utils.Logger;
import com.qianxx.utils.ToastUtil;
import com.squareup.leakcanary.LeakCanary;

import org.litepal.LitePalApplication;

import java.lang.reflect.Field;

/**
 * Created on 2016/11/17 上午9:49.
 *
 * @author binwin20
 */

public class BaseApplication extends LitePalApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        //initBaseConfig();
        ToastUtil.init(this);
        if (BaseConfig.DEBUG) {
            if (LeakCanary.isInAnalyzerProcess(this)) {
                // This process is dedicated to LeakCanary for heap analysis.
                // You should not init your app in this process.
                return;
            }
            LeakCanary.install(this);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    /**
     * 初始化 {@link BaseConfig} 用于 Tinker 热修复等
     */
    private void initBaseConfig() {
        try {
            String packageName = getPackageName();
            Class buildConfig = Class.forName(packageName + ".BuildConfig");    //获取对应类
            BaseConfig.PACKAGE_NAME = packageName;
            BaseConfig.CLIENT_TINKER_ID = getConfigField(buildConfig, "CLIENT_TINKER_ID");
            BaseConfig.PLATFORM = getConfigField(buildConfig, "PLATFORM");
            BaseConfig.DEBUG = getConfigField(buildConfig, "DEBUG");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        Logger.setDevelopMode(BaseConfig.DEBUG);
        Log.d("bin-->", "MyConfig.DEBUG=" + BaseConfig.DEBUG);
    }

    private <T> T getConfigField(Class buildConfig, String field) throws NoSuchFieldException, IllegalAccessException {
        Field field1 = buildConfig.getField(field);
        boolean access = field1.isAccessible();
        if (!access) field1.setAccessible(true);
        T value = (T) field1.get(buildConfig);
        if (!access) field1.setAccessible(false);
        return value;
    }
}
